package models.report;

import helpers.ClientRequest;

import java.util.*;

import play.Logger;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import play.data.validation.Constraints.*;
import play.data.format.*;
import play.mvc.Http.Context;
import play.mvc.Http.Request;
import service.Paging;

import javax.persistence.*;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.EbeanServer;
import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;
import com.avaje.ebean.PagingList;
import com.avaje.ebean.Query;
import com.avaje.ebean.RawSql;
import com.avaje.ebean.RawSqlBuilder;

@Entity
public class UsedCoin extends Model{
	public Integer dateKey;
	
	public String dateValue;
	
	public double price;
	
	public String type;

	public Integer appId;
	public Integer marketKey;
	public Integer deviceKey;
	
	// Extra: Product
	public Integer productId;
	public String productName;
	public Integer itemNums;
	public Integer userNums;
	public Integer usedCoin;
	
	public static Finder<Long,UsedCoin> find = new Finder(
		Long.class, UsedCoin.class
	);
	
	public static Paging search(String type, int startTime, int endTime){		
		Request request = Context.current().request();
		
		int pageSize = Integer.parseInt(request.getQueryString("pageSize"));
    	int page = Integer.parseInt(request.getQueryString("page"));
        
    	EbeanServer report = Ebean.getServer("report");
    	
    	String sql = "select date_value, product_id, product_name, type, item_nums, user_nums, used_coin" 
    		+ " from rpt_used_coin_daily";  
      
    	if(ClientRequest.getCurrent().marketKey == 0)
    	{
    		sql = " select date_value, product_id, product_name, type, SUM(item_nums) as itemNums, SUM(user_nums) as userNums, SUM(used_coin) as usedCoin "  
        			+ " from rpt_used_coin_daily "   
        			+ " group by date_value, product_id, type";  
    	}
    	
    	RawSql rawSql = RawSqlBuilder.parse(sql).create();
            
    	Query<UsedCoin> query = report.find(UsedCoin.class);
	    query.setRawSql(rawSql);
	    
    	ExpressionList<UsedCoin> expression = query.where();
    	
    	if(!type.isEmpty()) expression.eq("type", type);
    	
    	if(startTime > 0) expression.ge("date_key", startTime);
    	
    	if(endTime > 0) expression.le("date_key", endTime);
    	
    	expression = helpers.Query.addClientRequestExpression(expression);
    	
    	PagingList<UsedCoin> pagingList = expression.findPagingList(pageSize).setFetchAhead(false);
    	
    	Page<UsedCoin> page0 = pagingList.getPage(page - 1);
        List<UsedCoin> list = page0.getList();
        
    	Paging paging = new Paging(expression.findList().size(), list);
    	
        return paging;
	}
}
